// 导入所需模块
import { GameBoard } from './GameBoard.js';
import { GameRenderer } from './GameRenderer.js';
import { InputHandler } from './InputHandler.js';
import { AnimationManager } from './AnimationManager.js';
import { ScoreManager } from './ScoreManager.js';

// 游戏状态枚举
export const GameStatus = {
    INITIALIZING: 'INITIALIZING',
    READY: 'READY',
    PLAYING: 'PLAYING',
    SWAPPING: 'SWAPPING',
    MATCHING: 'MATCHING',
    FALLING: 'FALLING',
    PAUSED: 'PAUSED',
    GAME_OVER: 'GAME_OVER'
};

// 游戏引擎主控制器
export class GameEngine {
    constructor(containerElement) {
        this.container = containerElement;
        
        // 初始化游戏状态
        this.gameState = {
            status: GameStatus.INITIALIZING,
            score: 0,
            time: 0,
            combo: 0,
            isAnimating: false
        };

        // 初始化各个模块
        this.gameBoard = null;
        this.renderer = null;
        this.inputHandler = null;
        this.animationManager = null;
        this.scoreManager = null;
    }

    // 初始化游戏
    async init() {
        console.log('游戏引擎初始化中...');

        try {
            // 显示加载状态
            this.showLoadingState();

            // 检查设备性能
            const isHighPerformance = this.checkDevicePerformance();
            
            // 创建游戏模块
            this.gameBoard = new GameBoard(8, 8);
            this.renderer = new GameRenderer(this.container);
            this.inputHandler = new InputHandler(this);
            this.animationManager = new AnimationManager();
            this.scoreManager = new ScoreManager();

            // 检查渲染器性能
            this.renderer.checkPerformance();

            // 预加载资源
            await this.preloadResources();

            // 创建游戏网格DOM
            this.renderer.createGrid();

            // 渲染初始网格
            this.renderer.renderGrid(this.gameBoard);

            // 绑定事件
            this.inputHandler.bindEvents();
            this.inputHandler.bindKeyboardEvents();

            // 初始化UI
            this.renderer.updateScore(this.gameState.score);
            this.renderer.updateTimer(this.gameState.time);

            // 隐藏加载状态
            this.renderer.hideLoading();

            // 设置状态为就绪
            this.gameState.status = GameStatus.READY;

            console.log('游戏引擎初始化完成');
            
        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.handleInitError(error);
        }
    }

    // 显示加载状态
    showLoadingState() {
        if (this.renderer) {
            this.renderer.showLoading('正在初始化游戏...');
        }
    }

    // 检查设备性能
    checkDevicePerformance() {
        const performance = {
            cores: navigator.hardwareConcurrency || 1,
            memory: navigator.deviceMemory || 1,
            connection: navigator.connection?.effectiveType || 'unknown'
        };

        console.log('设备性能信息:', performance);

        // 根据性能调整设置
        if (performance.cores <= 2 || performance.memory <= 2) {
            console.log('检测到低端设备，启用性能优化');
            this.enablePerformanceMode();
            return false;
        }

        return true;
    }

    // 启用性能优化模式
    enablePerformanceMode() {
        document.body.classList.add('low-performance');
        
        // 可以在这里调整动画时长、减少特效等
        if (this.animationManager) {
            // 缩短动画时间
            this.animationManager.defaultDuration = 200;
        }
    }

    // 预加载资源
    async preloadResources() {
        return new Promise((resolve) => {
            // 模拟资源加载
            setTimeout(() => {
                if (this.renderer) {
                    this.renderer.preloadResources();
                }
                resolve();
            }, 100);
        });
    }

    // 处理初始化错误
    handleInitError(error) {
        this.gameState.status = GameStatus.GAME_OVER;
        
        if (this.renderer) {
            this.renderer.hideLoading();
            this.renderer.showError(`初始化失败: ${error.message}`);
        } else {
            // 如果渲染器都没创建成功，直接在容器中显示错误
            this.container.innerHTML = `
                <div class="game-error">
                    <h3>游戏加载失败</h3>
                    <p>${error.message}</p>
                    <button onclick="location.reload()">重新加载</button>
                </div>
            `;
        }
    }

    // 错误边界处理
    handleError(error, context = '游戏运行') {
        console.error(`${context}错误:`, error);
        
        // 记录错误到本地存储（用于调试）
        try {
            const errorLog = JSON.parse(localStorage.getItem('ghostMatchErrors') || '[]');
            errorLog.push({
                timestamp: new Date().toISOString(),
                context,
                message: error.message,
                stack: error.stack
            });
            
            // 只保留最近10个错误
            if (errorLog.length > 10) {
                errorLog.splice(0, errorLog.length - 10);
            }
            
            localStorage.setItem('ghostMatchErrors', JSON.stringify(errorLog));
        } catch (e) {
            console.warn('无法保存错误日志:', e);
        }

        // 显示用户友好的错误信息
        if (this.renderer) {
            this.renderer.showStatusMessage('游戏出现错误，请重试', 3000);
        }
    }

    // 开始游戏
    start() {
        if (this.gameState.status !== GameStatus.READY) {
            console.warn('游戏未就绪，无法开始');
            return;
        }

        console.log('游戏开始');
        this.gameState.status = GameStatus.PLAYING;
        
        // 开始计时
        this.scoreManager.startTimer((time) => {
            this.gameState.time = time;
            this.renderer.updateTimer(time);
        });

        // 隐藏覆盖层
        this.renderer.hideOverlay();
    }

    // 暂停游戏
    pause() {
        if (this.gameState.status === GameStatus.PLAYING) {
            console.log('游戏暂停');
            this.gameState.status = GameStatus.PAUSED;
            
            // 停止计时
            this.scoreManager.pauseTimer();
            
            // 禁用输入
            this.inputHandler.setEnabled(false);
            
            // 显示暂停覆盖层
            this.renderer.showOverlay('游戏暂停', '点击继续按钮恢复游戏', true);
        }
    }

    // 恢复游戏
    resume() {
        if (this.gameState.status === GameStatus.PAUSED) {
            console.log('游戏恢复');
            this.gameState.status = GameStatus.PLAYING;
            
            // 恢复计时
            this.scoreManager.resumeTimer();
            
            // 启用输入
            this.inputHandler.setEnabled(true);
            
            // 隐藏覆盖层
            this.renderer.hideOverlay();
        }
    }

    // 重置游戏
    reset() {
        console.log('游戏重置');
        
        // 停止所有动画
        this.animationManager.stopAllAnimations();
        
        // 重置游戏状态
        this.gameState = {
            status: GameStatus.INITIALIZING,
            score: 0,
            time: 0,
            combo: 0,
            isAnimating: false
        };

        // 重置各个模块
        this.gameBoard.regenerateGrid();
        this.scoreManager.reset();
        this.inputHandler.reset();

        // 重新渲染
        this.renderer.renderGrid(this.gameBoard);
        this.renderer.updateScore(this.gameState.score);
        this.renderer.updateTimer(this.gameState.time);
        this.renderer.hideOverlay();

        // 设置为就绪状态
        this.gameState.status = GameStatus.READY;
        
        // 自动开始游戏
        this.start();
    }

    // 处理交换操作
    async handleSwap(pos1, pos2) {
        if (this.gameState.status !== GameStatus.PLAYING || this.gameState.isAnimating) {
            return;
        }

        this.gameState.status = GameStatus.SWAPPING;
        this.gameState.isAnimating = true;

        try {
            // 执行交换动画
            await this.animationManager.swapAnimation(pos1, pos2, this.renderer);

            // 在数据模型中执行交换
            this.gameBoard.swapCells(pos1, pos2);

            // 更新渲染
            this.renderer.renderGrid(this.gameBoard);

            // 检查并处理匹配
            await this.processMatches();

        } catch (error) {
            console.error('交换处理失败:', error);
            this.handleError(error, '交换操作');
        } finally {
            this.gameState.isAnimating = false;
            if (this.gameState.status === GameStatus.SWAPPING) {
                this.gameState.status = GameStatus.PLAYING;
            }
        }
    }

    // 检查匹配
    checkMatches() {
        return this.gameBoard.findMatches();
    }

    // 处理匹配
    async processMatches() {
        let totalMatches = 0;
        this.gameState.combo = 0;

        while (true) {
            // 检查匹配
            const matches = this.checkMatches();
            
            if (matches.length === 0) {
                break; // 没有更多匹配
            }

            this.gameState.status = GameStatus.MATCHING;
            this.gameState.combo++;
            totalMatches += matches.length;

            // 播放匹配动画
            await this.animationManager.matchAnimation(matches, this.renderer);

            // 移除匹配的单元格
            const removedCells = this.gameBoard.removeMatches(matches);

            // 计算分数
            const points = this.scoreManager.calculateScore(removedCells.length, this.gameState.combo);
            this.gameState.score += points;
            this.renderer.updateScore(this.gameState.score);

            // 显示连击效果
            if (this.gameState.combo > 1) {
                this.renderer.updateCombo(this.gameState.combo);
            }

            // 应用重力
            await this.applyGravity();

            // 填充新单元格
            const newCells = this.gameBoard.fillEmptySpaces();
            
            if (newCells.length > 0) {
                // 更新渲染
                this.renderer.renderGrid(this.gameBoard);
                
                // 播放新单元格动画
                await this.animationManager.newCellAnimation(newCells, this.renderer);
            }
        }

        // 重置连击
        this.gameState.combo = 0;
        
        // 恢复游戏状态为可交互
        this.gameState.status = GameStatus.PLAYING;
        
        // 检查是否还有可能的移动
        if (!this.hasPossibleMoves()) {
            this.handleNoMoves();
        }
    }

    // 应用重力效果
    async applyGravity() {
        this.gameState.status = GameStatus.FALLING;

        // 计算重力移动
        const moves = this.gameBoard.applyGravity();

        if (moves.length > 0) {
            // 更新渲染
            this.renderer.renderGrid(this.gameBoard);
            
            // 播放下落动画
            await this.animationManager.fallAnimation(moves, this.renderer);
        }
    }

    // 检查是否有可能的移动
    hasPossibleMoves() {
        for (let x = 0; x < 8; x++) {
            for (let y = 0; y < 8; y++) {
                // 检查右边的交换
                if (x < 7 && this.gameBoard.isValidSwap({x, y}, {x: x + 1, y})) {
                    return true;
                }
                // 检查下边的交换
                if (y < 7 && this.gameBoard.isValidSwap({x, y}, {x, y: y + 1})) {
                    return true;
                }
            }
        }
        return false;
    }

    // 处理无可移动情况
    handleNoMoves() {
        console.log('没有可能的移动，重新生成网格');
        this.gameBoard.regenerateGrid();
        this.renderer.renderGrid(this.gameBoard);
        this.renderer.showStatusMessage('网格已重新生成！', 2000);
    }

    // 检查是否可以交互
    canInteract() {
        const canInteract = this.gameState.status === GameStatus.PLAYING && !this.gameState.isAnimating;
        console.log(`游戏交互状态: status=${this.gameState.status}, isAnimating=${this.gameState.isAnimating}, canInteract=${canInteract}`);
        return canInteract;
    }

    // 检查是否暂停
    isPaused() {
        return this.gameState.status === GameStatus.PAUSED;
    }

    // 获取游戏状态
    getGameState() {
        return { ...this.gameState };
    }

    // 更新游戏循环
    update() {
        // 这里可以添加需要每帧更新的逻辑
        // 目前主要由事件驱动，暂时不需要
    }
}